﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    ViewData["Title"] = "设备台账管理";
    Layout = null;
}

@Html.AntiForgeryToken()

<!-- 先加载CSS -->
<link href="https://cdn.bootcdn.net/ajax/libs/layui/2.6.8/css/layui.min.css" rel="stylesheet">

<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-header">
            <h3>设备台账管理</h3>
        </div>
        <div class="layui-card-body">
            <div class="layui-row layui-col-space15">
                <!-- 左侧设备分类树 -->
                <div class="layui-col-md3">
                    <div class="layui-card">
                        <div class="layui-card-header">设备分类</div>
                        <div class="layui-card-body">
                            <div id="equipmentTypeTree"></div>
                            <div class="layui-form-item" style="margin-top: 15px; text-align: center;" id="selectedTypeContainer">
                                <button type="button" class="layui-btn layui-btn-primary layui-btn-xs" id="clearTreeFilter" style="display: none;">
                                    <i class="layui-icon layui-icon-close"></i> 清除筛选
                                </button>
                                <div class="selected-type-text" id="selectedTypeText"></div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 右侧内容区 -->
                <div class="layui-col-md9">
                    <!-- 搜索表单 -->
                    <div class="layui-form search-form" lay-filter="searchForm">
                        <div class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label">设备编号</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="deviceCode" placeholder="请输入设备编号" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-inline">
                                <label class="layui-form-label">设备名称</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="deviceName" placeholder="请输入设备名称" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-inline">
                                <button type="button" class="layui-btn" id="searchBtn">
                                    <i class="layui-icon layui-icon-search"></i> 搜索
                                </button>
                                <button type="button" class="layui-btn layui-btn-primary" id="resetBtn">重置</button>
                            </div>
                        </div>
                    </div>

                    <!-- 工具栏 -->
                    <div class="layui-btn-group table-tool-btn">
                        <button class="layui-btn" id="addBtn">
                            <i class="layui-icon layui-icon-add-1"></i> 添加
                        </button>
                        <button class="layui-btn layui-btn-danger" id="batchDeleteBtn">
                            <i class="layui-icon layui-icon-delete"></i> 批量删除
                        </button>
                        <button class="layui-btn layui-btn-normal" id="refreshBtn">
                            <i class="layui-icon layui-icon-refresh"></i> 刷新
                        </button>
                    </div>

                    <!-- 数据表格 -->
                    <table id="mainTable" lay-filter="mainTable"></table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 表单模板 -->
<script type="text/html" id="formTpl">
    <form class="layui-form" lay-filter="mainForm" style="margin: 20px;">
        <input type="hidden" name="Id">
        <div class="layui-form-item">
            <label class="layui-form-label required">设备编号</label>
            <div class="layui-input-block">
                <input type="text" name="DeviceCode" required lay-verify="required" placeholder="请输入设备编号" autocomplete="off" class="layui-input">
                <div class="layui-btn-container" style="margin-top: 5px;">
                    <div class="auto-generate-switch">
                        <span>自动生成</span>
                        <input type="checkbox" id="autoGenerateSwitch" lay-skin="switch" lay-filter="autoGenerateSwitch" lay-text="开|关">
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label required">设备名称</label>
            <div class="layui-input-block">
                <input type="text" name="DeviceName" required lay-verify="required" placeholder="请输入设备名称" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">品牌</label>
            <div class="layui-input-block">
                <input type="text" name="Brand" placeholder="请输入品牌" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label required">设备分类</label>
            <div class="layui-input-block">
                <select name="EquipmentTypeCode" id="deviceTypeSelect" required lay-verify="required">
                    <option value="">请选择设备分类</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">规格型号</label>
            <div class="layui-input-block">
                <input type="text" name="Specification" placeholder="请输入规格型号" autocomplete="off" class="layui-input">
            </div>
        </div>
        
         <div class="layui-form-item">
            <label class="layui-form-label">所属车间</label>
            <div class="layui-input-block">
                <select name="Workshop">
                    <option value="">请选择车间</option>
                    <option value="机加工车间">机加工车间</option>
                    <option value="装配车间">装配车间</option>
                    <option value="焊接车间">焊接车间</option>
                    <option value="热处理车间">热处理车间</option>
                    <option value="表面处理车间">表面处理车间</option>
                    <option value="检测车间">检测车间</option>
                    <option value="包装车间">包装车间</option>
                </select>
            </div>
        </div>


        <div class="layui-form-item layui-form-text">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-block">
                <textarea name="Note" placeholder="请输入备注" class="layui-textarea"></textarea>
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button type="button" class="layui-btn" id="submitBtn">提交</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>
</script>

<!-- 工具条模板 -->
<script type="text/html" id="tableBar">
    <div class="layui-btn-group">
        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </div>
</script>

<!-- 先加载jQuery，再加载Layui -->
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/layui/2.6.8/layui.min.js"></script>

<script>
    layui.use(['table', 'form', 'layer', 'tree'], function(){
        var table = layui.table;
        var form = layui.form;
        var layer = layui.layer;
        var tree = layui.tree;
        var $ = layui.$;
        
        // 当前选中的设备分类ID
        var equipmentTypeCode = '';
        // 设备分类树数据
        var equipmentTypeData = [];
        // 车间列表数据
        // var workshopData = [];
        
        // 初始化页面
        initPage();
        
        function initPage() {
            // 加载设备分类树
            loadEquipmentTypeTree();
          
            // 初始化表格
            initTable();
            // 绑定事件
            bindEvents();
        }
        
        // 初始化表格
        function initTable(params) {
            var queryParams = params || {};
            queryParams.__RequestVerificationToken = $('input[name="__RequestVerificationToken"]').val();
            
            table.render({
                elem: '#mainTable',
                url: '/DeviceLedger/List',
                method: 'post',
                where: queryParams,
                page: true,
                limit: 10,
                limits: [10, 20, 50, 100],
                request: {
                    pageName: 'page',
                    limitName: 'limit'
                },
                parseData: function(res) {
                    return {
                        "code": res.code === 0 ? 0 : 1,
                        "msg": res.msg || '',
                        "count": res.count || res.total || 0,
                        "data": res.data || []
                    };
                },
                cols: [[
                    {type: 'checkbox', fixed: 'left'},
                    {field: 'deviceCode', title: '设备编号', width: 120},
                    {field: 'deviceName', title: '设备名称', width: 150},
                    {field: 'brand', title: '品牌', width: 120},
                    {field: 'equipmentTypeName', title: '设备分类', width: 120},
                    {field: 'specification', title: '规格型号', width: 120},
                    {field: 'workshop', title: '所属车间', width: 120},
                    {field: 'note', title: '备注', width: 200},
                    {fixed: 'right', title: '操作', toolbar: '#tableBar', width: 120}
                ]],
                skin: 'line',
                even: true,
                size: 'lg',
                text: {
                    none: '暂无设备台账数据'
                }
            });
        }
        // 加载设备分类树
        function loadEquipmentTypeTree() {
            $.ajax({
                url: '/DeviceLedger/GetEquipmentTypeTree',
                type: 'GET',
                success: function(res) {
                    if(res.code === 0 && res.data) {
                        equipmentTypeData = res.data;
                        console.log('设备分类树数据:', res.data);
                        
                        // 转换数据格式以适配layui tree
                        var treeData = res.data.map(function(item) {
                            return {
                                id: item.id, // 使用设备类型编码作为ID
                                title: item.title, // 显示名称
                                spread: false // 默认收起
                            };
                        });
                        
                        console.log('转换后的树数据:', treeData);
                        
                        tree.render({
                            elem: '#equipmentTypeTree',
                            data: treeData,
                            showCheckbox: false,
                            showLine: true,
                            accordion: false,
                            onlyIconControl: false,
                            view: {
                                showIcon: false,
                                showLine: true
                            },
                            click: function(obj) {
                                // 直接使用equipmentTypeCode
                                equipmentTypeCode = obj.data.id;
                                console.log('选中的设备类型编码:', equipmentTypeCode);
                                console.log('选中的节点数据:', obj.data);
                                
                                // 重新加载表格数据
                                reloadTable();
                                
                                // 显示当前选中的分类名称
                                $('#selectedTypeText').text('当前筛选: ' + obj.data.title);
                                $('#clearTreeFilter').show();
                            }
                        });
                    } else {
                        layer.msg('加载设备分类失败：' + (res.msg || '未知错误'));
                    }
                },
                error: function(xhr) {
                    layer.msg('加载设备分类失败：' + (xhr.responseJSON?.msg || '服务器错误'));
                    console.error('加载设备分类错误:', xhr);
                }
            });
        }
      
        
        // 加载设备分类下拉选项
        function loadDeviceTypeSelect(selectElem, selectedValue) {
            $.ajax({
                url: '/DeviceLedger/GetEquipmentTypeList',
                type: 'GET',
                success: function(res) {
                    if(res.code === 0 && res.data) {
                        var $select = $(selectElem);
                        $select.empty().append('<option value="">请选择设备分类</option>');
                        
                        $.each(res.data, function(index, item) {
                            // 确保使用equipmentTypeCode作为value值
                            $select.append('<option value="' + item.equipmentTypeCode + '">' + item.equipmentTypeName + '</option>');
                        });
                        
                        if(selectedValue) {
                            $select.val(selectedValue);
                            console.log("设置选中值:", selectedValue);
                        }
                        
                        form.render('select');
                    } else {
                        layer.msg('加载设备分类失败：' + (res.msg || '未知错误'));
                    }
                },
                error: function(xhr) {
                    layer.msg('加载设备分类失败：' + (xhr.responseJSON?.msg || '服务器错误'));
                }
            });
        }
        
        // 重新加载表格数据
        function reloadTable() {
            var queryParams = getSearchParams();
            console.log('重新加载表格数据，参数:', queryParams);
            
            table.reload('mainTable', {
                where: queryParams,
                page: {
                    curr: 1
                }
            });
        }
        
        // 获取搜索参数
        function getSearchParams() {
            var formData = form.val('searchForm');
            var params = {
                deviceCode: formData.deviceCode || '',
                deviceName: formData.deviceName || '',
                equipmentTypeCode: equipmentTypeCode || '',
                __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
            };
            console.log('搜索参数:', params);
            return params;
        }
        
        // 绑定事件
        function bindEvents() {
            // 搜索按钮点击事件
            $('#searchBtn').on('click', function() {
                reloadTable();
            });
            
            // 重置按钮点击事件
            $('#resetBtn').on('click', function() {
                form.val('searchForm', {
                    deviceCode: '',
                    deviceName: ''
                });
                equipmentTypeCode = '';
                $('#selectedTypeText').text('');
                $('#clearTreeFilter').hide();
                reloadTable();
            });
            
            // 清除树筛选按钮点击事件
            $('#clearTreeFilter').on('click', function() {
                equipmentTypeCode = '';
                $('#selectedTypeText').text('');
                $(this).hide();
                console.log('清除了设备类型筛选');
                reloadTable();
            });
            
            // 添加按钮点击事件
            $('#addBtn').on('click', function() {
                openForm();
            });
            
            // 批量删除按钮点击事件
            $('#batchDeleteBtn').on('click', function() {
                var checkStatus = table.checkStatus('mainTable');
                var data = checkStatus.data;
                
                if(data.length === 0) {
                    layer.msg('请至少选择一条记录');
                    return;
                }
                
                var ids = data.map(function(item) {
                    return item.id;
                });
                
                layer.confirm('确定要删除选中的 ' + data.length + ' 条设备记录吗？', function(index) {
                    // 构建表单数据
                    var formData = new FormData();
                    ids.forEach(function(id, index) {
                        formData.append('ids[' + index + ']', id);
                    });
                    formData.append('__RequestVerificationToken', $('input[name="__RequestVerificationToken"]').val());
                    
                    $.ajax({
                        url: '/DeviceLedger/BatchDelete',
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function(res) {
                            if(res.code === 0) {
                                layer.msg(res.msg || '批量删除成功');
                                reloadTable();
                            } else {
                                layer.msg('删除失败：' + (res.msg || '未知错误'));
                            }
                        },
                        error: function(xhr) {
                            layer.msg('删除失败：' + (xhr.responseJSON?.msg || '服务器错误'));
                        }
                    });
                    
                    layer.close(index);
                });
            });
            
            // 刷新按钮点击事件
            $('#refreshBtn').on('click', function() {
                loadEquipmentTypeTree();
                reloadTable();
            });
            
            // 监听工具条事件
            table.on('tool(mainTable)', function(obj) {
                var data = obj.data;
                
                if(obj.event === 'edit') {
                    // 编辑操作
                    $.ajax({
                        url: '/DeviceLedger/GetById',
                        type: 'GET',
                        data: {
                            id: data.id
                        },
                        success: function(res) {
                            if(res.code === 0 && res.data) {
                                openForm(res.data);
                            } else {
                                layer.msg('获取设备详情失败：' + (res.msg || '未知错误'));
                            }
                        },
                        error: function(xhr) {
                            layer.msg('获取设备详情失败：' + (xhr.responseJSON?.msg || '服务器错误'));
                        }
                    });
                } else if(obj.event === 'del') {
                    // 删除操作
                    layer.confirm('确定要删除此设备吗？', function(index) {
                        $.ajax({
                            url: '/DeviceLedger/Delete',
                            type: 'POST',
                            data: {
                                id: data.id,
                                __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
                            },
                            success: function(res) {
                                if(res.code === 0) {
                                    layer.msg('删除成功');
                                    obj.del();
                                } else {
                                    layer.msg('删除失败：' + (res.msg || '未知错误'));
                                }
                            },
                            error: function(xhr) {
                                layer.msg('删除失败：' + (xhr.responseJSON?.msg || '服务器错误'));
                            }
                        });
                        
                        layer.close(index);
                    });
                }
            });
        }
        
        // 打开表单
        function openForm(data) {
            var title = data ? '编辑设备' : '添加设备';
            
            layer.open({
                type: 1,
                title: title,
                area: ['600px', '650px'],
                content: $('#formTpl').html(),
                success: function(layero, index) {
                    // 加载设备分类下拉选项
                    loadDeviceTypeSelect('#deviceTypeSelect', data ? data.equipmentTypeCode : equipmentTypeCode);
                    
                    // 表单赋值
                    if(data) {
                        form.val('mainForm', {
                            Id: data.id,
                            DeviceCode: data.deviceCode,
                            DeviceName: data.deviceName,
                            Brand: data.brand,
                            EquipmentTypeCode: data.equipmentTypeCode,
                            Specification: data.specification,
                            Workshop: data.workshop,
                            Note: data.note
                        });
                    }
                    
                    // 重新渲染表单
                    form.render(null, 'mainForm');
                    
                    // 绑定自动生成设备编号开关事件
                    form.on('switch(autoGenerateSwitch)', function(data) {
                        if(data.elem.checked) {
                            var loadIndex = layer.load(2);
                            
                            // 调用后端生成设备编号
                            $.ajax({
                                url: '/DeviceLedger/GenerateDeviceCode',
                                type: 'GET',
                                success: function(res) {
                                    layer.close(loadIndex);
                                    
                                    if(res.code === 0 && res.deviceCode) {
                                        // 设置设备编号
                                        $('input[name="DeviceCode"]').val(res.deviceCode);
                                    } else {
                                        layer.msg('生成设备编号失败：' + (res.msg || '未知错误'));
                                        // 开关切回关闭状态
                                        data.elem.checked = false;
                                        form.render('checkbox');
                                    }
                                },
                                error: function(xhr) {
                                    layer.close(loadIndex);
                                    layer.msg('生成设备编号失败：' + (xhr.responseJSON?.msg || '服务器错误'));
                                    // 开关切回关闭状态
                                    data.elem.checked = false;
                                    form.render('checkbox');
                                }
                            });
                        } else {
                            // 清空设备编号
                            $('input[name="DeviceCode"]').val('');
                        }
                    });
                    
                    // 监听提交按钮点击事件
                    $(layero).find('#submitBtn').off('click').on('click', function() {
                        // 获取表单数据
                        var formData = form.val('mainForm');
                        
                        // 表单验证
                        if (!formData.DeviceCode) {
                            layer.msg('请输入设备编号');
                            return;
                        }
                        
                        if (!formData.DeviceName) {
                            layer.msg('请输入设备名称');
                            return;
                        }
                        
                        // 检查设备分类
                        if (!formData.EquipmentTypeCode) {
                            layer.msg('请选择设备分类');
                            return;
                        }
                        
                        // 检查设备编号是否已存在（编辑时检查编号是否与其他设备重复）
                        var isEdit = formData.Id && Number(formData.Id) > 0;
                        var loadIndex = layer.load(2);
                        
                        $.ajax({
                            url: '/DeviceLedger/CheckDeviceCodeExists',
                            type: 'GET',
                            data: { deviceCode: formData.DeviceCode },
                            success: function(checkRes) {
                                if(checkRes.code === 0) {
                                    // 如果是新增，或者是编辑但编号已变更，则检查是否重复
                                    var originalDeviceCode = data ? data.deviceCode : '';
                                    if(checkRes.exists && (!isEdit || (isEdit && formData.DeviceCode !== originalDeviceCode))) {
                                        layer.close(loadIndex);
                                        layer.msg('设备编号已存在，请更换其他编号');
                                        return;
                                    }
                                    
                                    // 添加token
                                    formData.__RequestVerificationToken = $('input[name="__RequestVerificationToken"]').val();
                                    
                                    console.log("提交的表单数据:", formData);
                                    
                                    // 提交表单
                                    $.ajax({
                                        url: isEdit ? '/DeviceLedger/Update' : '/DeviceLedger/AddDeviceLedger',
                                        type: 'POST',
                                        data: formData,
                                        success: function(res) {
                                            layer.close(loadIndex);
                                            console.log("服务器响应:", res);
                                            
                                            if(res.code === 0) {
                                                layer.close(index);
                                                layer.msg(isEdit ? '编辑成功' : '添加成功');
                                                reloadTable();
                                            } else {
                                                layer.msg((isEdit ? '编辑' : '添加') + '失败：' + (res.msg || '未知错误'));
                                            }
                                        },
                                        error: function(xhr) {
                                            layer.close(loadIndex);
                                            console.error('提交错误:', xhr);
                                            console.error('提交的数据:', formData);
                                            console.error('设备分类值:', formData.EquipmentTypeCode);
                                            layer.msg((isEdit ? '编辑' : '添加') + '失败：' + (xhr.responseJSON?.msg || '服务器错误'));
                                        }
                                    });
                                } else {
                                    layer.close(loadIndex);
                                    layer.msg('检查设备编号失败：' + (checkRes.msg || '未知错误'));
                                }
                            },
                            error: function(xhr) {
                                layer.close(loadIndex);
                                layer.msg('检查设备编号失败：' + (xhr.responseJSON?.msg || '服务器错误'));
                            }
                        });
                    });
                }
            });
        }
    });
</script>

<style>
    .layui-form-label.required:after {
        content: '*';
        color: red;
        position: absolute;
        margin-left: 4px;
        font-weight: bold;
    }
    
    #equipmentTypeTree {
        min-height: 400px;
        overflow: auto;
    }
    
    /* 调整树节点的样式 */
    .layui-tree-entry {
        padding: 6px 0;
    }
    
    .layui-tree-txt {
        color: #333;
        font-size: 14px;
    }
    
    /* 隐藏节点前的小圆点 */
    .layui-tree-iconClick .layui-tree-icon {
        display: none;
    }
    
    .table-tool-btn {
        margin-bottom: 10px;
    }
    
    .search-form {
        margin-bottom: 15px;
        padding: 15px;
        background-color: #f8f8f8;
        border-radius: 4px;
    }
    
    .selected-type-text {
        margin-top: 5px;
        color: #009688;
        font-weight: bold;
    }
    
    #selectedTypeContainer {
        border-top: 1px dashed #eee;
        padding-top: 10px;
    }

    /* 自动生成开关样式 */
    .auto-generate-switch {
        display: flex;
        align-items: center;
        margin-top: 8px;
    }
    
    .auto-generate-switch span {
        margin-right: 10px;
        font-size: 14px;
    }
    
    /* 自定义开关颜色为绿色 */
    .layui-form-onswitch {
        background-color: #5FB878 !important;
        border-color: #5FB878 !important;
    }
</style>
